﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CashFlow.Web.Models;
using System.Security.Principal;
using CashFlow.Entities;

namespace CashFlow.Web
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
					"CashFlow", // Route name
					"CashFlow", // URL with parameters
					new { controller = "CashFlow", action = "List"} // Parameter defaults
			);

			routes.MapRoute(
					"Bills", // Route name
					"Bills", // URL with parameters
					new { controller = "Bill", action = "Index", id = UrlParameter.Optional } // Parameter defaults
			);

			routes.MapRoute(
					"Default", // Route name
					"{controller}/{action}/{id}", // URL with parameters
					new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
			);

		}

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);
		}

		public override void Init()
		{
			this.AuthenticateRequest += (s, e) => { };
			this.PostAuthenticateRequest += (s, e) => AppPostAuthenticateRequest(s, e);
			base.Init();
		}

		private void AppPostAuthenticateRequest(object sender, EventArgs e)
		{
			var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
			var principal = GetPrincipal(authCookie);
			if (principal != null)
			{
					HttpContext.Current.User = principal;
			}
		}

		private GenericPrincipal GetPrincipal(HttpCookie cookie)
		{
			GenericPrincipal principal = null;
			if (cookie != null)
			{
				var encryptedTicket = cookie.Value;
				if (!String.IsNullOrEmpty(encryptedTicket))
				{
					var ticket = FormsAuthentication.Decrypt(encryptedTicket);
					var identity = new AppIdentity(ticket);
					principal = new GenericPrincipal(identity, null);
				}
			}

			return principal;
		}

	}
}